package net.sxjr.protal.user;

import com.alibaba.fastjson.JSON;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import lombok.extern.slf4j.Slf4j;
import net.sxjr.common.FileTypeUtils;
import net.sxjr.common.GlobalParam;
import net.sxjr.common.RedisService;
import net.sxjr.common.Response;
import net.sxjr.mbg.entity.SysUploadFile;
import net.sxjr.mbg.mapper.SysUploadFileMapper;
import net.sxjr.protal.user.dao.LoginUserInfo;
import net.sxjr.protal.user.params.FileUploadParams;
import net.sxjr.protal.user.params.LoginParams;
import net.sxjr.protal.user.service.LoginService;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：cuixc
 * @date ：Created in 2020/12/10 15:36
 * @description：登陆控制器
 * @modified By：
 */
@RestController
@RequestMapping("/home")
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Response login(@RequestBody LoginParams loginParam, HttpServletResponse response){
        Response<LoginUserInfo> login = loginService.login(loginParam);
        if(login.getCode() == 200){
            LoginUserInfo data = login.getData();
            if(data != null){
                response.setHeader("token",data.getUserId());
            }
        }
        return login;
    }

    //获取组织结构人员列表
    @GetMapping("/getUserList")
    public Response getUserList(){
        return loginService.getUserList();
    }

    //监督编码
    @GetMapping("/superviseCode")
    public Response superviseCode(@RequestParam String code){
        return loginService.superviseCode(code);
    }

    //环节编码
    @GetMapping("/linkcode")
    public Response linkcode(@RequestParam String supervisionTypeName){
        return loginService.linkcode(supervisionTypeName);
    }


    //上传文件
    @PostMapping("/fileUpload")
    public Response fileUpload(@RequestParam("files") MultipartFile[] files, FileUploadParams params){

        // 上传到服务器
        String path = System.getProperty("catalina.home") + "\\webapps" + GlobalParam.FILE_PATH;
        String savePath =  GlobalParam.FILE_PATH;

        List<String> uris = new ArrayList<>();
        for (MultipartFile file : files) {
            //判断文件是否为空
            if(file.isEmpty()){
                return Response.error(600,"文件为空");
            }

            //创建输入输出流
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                //指定上传的位置为 d:/upload/

                //获取文件的输入流
                inputStream = file.getInputStream();
                //获取上传时的文件名
                String fileName = file.getOriginalFilename();
                String fileType = FileTypeUtils.getFileTypeBySuffix(fileName);
                FastDateFormat df = FastDateFormat.getInstance("yyyyMMddHHmmssSSS");
                String s = df.format(new Date());
                String uploadFileName = s+"."+fileType;
                String uriName = path+uploadFileName;
                //注意是路径+文件名
                File targetFile = new File(uriName);
                //如果之前的 String path = "d:/upload/" 没有在最后加 / ，那就要在 path 后面 + "/"

                //判断文件父目录是否存在
                if(!targetFile.getParentFile().exists()){
                    //不存在就创建一个
                    targetFile.getParentFile().mkdir();
                }

                //获取文件的输出流
                outputStream = new FileOutputStream(targetFile);
                //最后使用资源访问器FileCopyUtils的copy方法拷贝文件
                FileCopyUtils.copy(inputStream, outputStream);

                //处理系统附件上传表
                SysUploadFile uploadFile = new SysUploadFile();
                uploadFile.setMainId(params.getMainId());
                uploadFile.setMainType(params.getMainType());
                uploadFile.setFileName(fileName);
                uploadFile.setFileType(fileType);
                uploadFile.setFileUrl(savePath+uploadFileName);
                LoginUserInfo currentUser = loginService.getCurrentUser();
                uploadFile.setDoUser(currentUser.getUserName());
                uploadFile.setDoTime(new Date());
                uploadFile.setDeptId(loginService.getUserinfo(currentUser.getAccount()).getDeptId());
                log.info("文件上传  {} ",JSON.toJSONString(uploadFile));
                uploadFile.insert();
                uris.add(s+"."+fileType);
            } catch (IOException e) {
                e.printStackTrace();
                //出现异常，则告诉页面失败
                log.error("上传文件失败");
            } finally {
                //无论成功与否，都有关闭输入输出流
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return Response.success(uris);
    }

    @GetMapping("/getfile")
    public Response getfile(String mainId,String mainType){
        return loginService.getfile(mainId,mainType);
    }
}
